package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.dto.pojo.SpecGroupDTO;
import com.leyou.dto.pojo.SpecParamDTO;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HeGuanChao
 * @Description TODO 规格service
 * @Date 2020/4/1 11:08
 */
@Service
public class SpecService {
    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;


    public List<SpecGroupDTO> querySpecGroupByCid(Long id) {
        // 创建规格组对象
        SpecGroup specGroup = new SpecGroup();
        // 设置分类id
        specGroup.setCid(id);
        // 查询数据库
        List<SpecGroup> specGroups = specGroupMapper.select(specGroup);
        // 判空
        if (CollectionUtils.isEmpty(specGroups)) {
            // 列表为空，抛出异常
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(specGroups, SpecGroupDTO.class);
    }

    public List<SpecParamDTO> querySpecParamByGid(Long gid, Long cid, Boolean searching) {
        // 要求规格组和商品分类至少有一个
        if (gid != null && cid != null) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        // 创建对象，设置参数
        SpecParam specParam = new SpecParam();
        specParam.setCid(cid);
        specParam.setGroupId(gid);
        specParam.setSearching(searching);
        // 查询数据
        List<SpecParam> specParams = specParamMapper.select(specParam);
        // 判空
        if (CollectionUtils.isEmpty(specParams)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        // 封装并返回数据
        return BeanHelper.copyWithCollection(specParams, SpecParamDTO.class);
    }

    public List<SpecGroupDTO> querySpecsByCid(Long id) {
        // 查询规格组
        List<SpecGroupDTO> specGroupDTOS = querySpecGroupByCid(id);
        // 查询组内参数
        List<SpecParamDTO> specParamDTOS = querySpecParamByGid(null, id, null);
        // 把groupId相同的放到一个集合中 groupingBy()把相同的数据分到同一个组内
        Map<Long, List<SpecParamDTO>> map = specParamDTOS.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        // 遍历把规格参数赋值给SpecGroupDTO的params
        for (SpecGroupDTO specGroupDTO : specGroupDTOS) {
            specGroupDTO.setParams(map.get(specGroupDTO.getId()));
        }

        // 返回数据
        return specGroupDTOS;
    }
}
